<?php

namespace app\admin\controller\oa;

use app\common\controller\Backend;
use think\Db;
use think\Env;
//use think\exception\ValidateException;

/**
 * 出差
 *
 * @icon fa fa-table
 * @remark 当一个页面上存在多个Bootstrap-table时该如何控制按钮和表格
 */
class Evection extends Backend
{
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];
    protected $relationSearch = true;

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;
    protected $categorylist = [];
    private $redis;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Evection;
        $this->redis = redis(Env::get('redis.host'), Env::get('redis.port'), Env::get('redis.pwd'), Env::get('redis.db'));

        $admin_arr = Db::table('fa_admin')
            ->field('id,nickname')
            ->where('status','normal')
            ->where('id','<>',$this->auth->id)
            ->select();

        $examine = Db::table('fa_oa_examine')
            ->alias('a')
            ->field('b.id,b.nickname,b.avatar')
            ->join('fa_admin b','a.admin_id=b.id','left')
            ->where('a.oa_id',3)
            ->order('a.type','asc')
            ->select();

        $count = count($examine);

        $this->view->assign("arr", $admin_arr);
        $this->view->assign("examine", $examine);
        $this->view->assign("count", $count);
    }

    /**
     * 查看
     */
    public function index()
    {

        if (isset(request()->param()['is'])){
            $is = request()->param()['is'];
        }else{
            $is =2;
        }

        if (isset(request()->param()['is_comment'])){
            $is_comment = request()->param()['is_comment'];
        }else{
            $is_comment = '';
        }

        $this->view->assign("is", $is);
        $this->assignconfig('is_comment',$is_comment);
        return $this->view->fetch();
    }

    public function table1()
    {
        $this->model = model('Evection');
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with([
                    'admin' => function ($query) {
                        $query->withField('id,nickname,avatar');
                    }
                ])
                ->where($where)
                ->where('admin_id',$this->auth->id)
                ->order('id', 'desc')
                ->paginate($limit);

            if (!empty($list->items())){
                foreach ($list->items() as $k=>$v){
                    $list->items()[$k]['names'] = $v->admin['nickname'].'提交的出差';
                }
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch('index');
    }

    public function table2()
    {
        $this->model = model('Relation');
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            if (request()->param()['is_comment'] == 1){
                $wheres['relation.is_comment'] = 0;
            }else{
                $wheres = [];
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with([
                    'evection' => function ($query) {
                        $query->withField('id,admin_id,create_time,status,msg');
                    }
                ])
                ->where($where)
                ->where($wheres)
                ->where('relation.admin_id',$this->auth->id)
                ->where('relation.status',4)
                ->where('relation.type',0)
                ->order('id', 'desc')
                ->paginate($limit);

            if (!empty($list->items())){
                foreach ($list->items() as $k=>$v){
                    $name = Db::table('fa_admin')
                        ->field('id,nickname,avatar')
                        ->where('id',$v->evection['admin_id'])
                        ->find();
                    $list->items()[$k]['name'] = $name['nickname'].'提交的出差';
                }
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch('index');
    }

    public function table3()
    {
        $this->model = model('Relation');
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with([
                    'evection' => function ($query) {
                        $query->withField('id,admin_id,create_time,status,msg');
                    }
                ])
                ->where($where)
                ->where('relation.admin_id',$this->auth->id)
                ->where('relation.status',4)
                ->where('relation.type',1)
                ->order('id', 'desc')
                ->paginate($limit);

            if (!empty($list->items())){
                foreach ($list->items() as $k=>$v){
                    $name = Db::table('fa_admin')
                        ->field('id,nickname,avatar')
                        ->where('id',$v->evection['admin_id'])
                        ->find();
                    $list->items()[$k]['name'] = $name['nickname'].'提交的出差';
                }
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch('index');
    }


    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }

                if (empty($params['id'])){
                    $this->error(__('审批人不能为空'));
                }


                if (count(explode(',',$params['images'])) > 9){
                    $this->error(__('数量最大添加9张'));
                }


                $params['admin_id'] = $this->auth->id;
                $params['code'] = get_strings(10,2);
                $ids_arr = $params['ids'];
                $id_arr = $params['id'];

                $site_arr = $params['site'];
                $start_time_arr = $params['start_time'];
                $end_time_arr = $params['end_time'];
                $day_arr = $params['day'];

                $params['ids'] = implode(',',$params['id']);
                unset($params['id']);

                unset($params['site']);
                unset($params['start_time']);
                unset($params['end_time']);
                unset($params['day']);

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }

                    $result = $this->model->allowField(true)->save($params);

                    $id = $this->model->id;//新增的id

                    $details = [];
                    foreach ($site_arr as $k=>$v){
                        $details[$k] = [
                            'oa_id' => $id,
                            'site' => $v,
                            'start_time' => $start_time_arr[$k],
                            'end_time' => $end_time_arr[$k],
                            'day' => $day_arr[$k],
                            'create_time' => time(),
                        ];

                    }

                    $insertall = Db::table('fa_oa_route')
                        ->insertAll($details);


                    $arr = [];
                    if (!empty($ids_arr)){
                        foreach ($ids_arr as $k=>$v){
                            $arr[$k] = [
                                'log_id' => $id,
                                'admin_id' => $v,
                                'create_time' => time(),
                                'is_comment' => 0,
                                'status' => 4,
                                'type' => 1,
                            ];
                        }

                        $inserts = Db::table('fa_oa_relation')
                            ->insertAll($arr);
                    }else{
                        $inserts = 1;
                    }


                    $insertss = Db::table('fa_oa_relation')
                        ->insertGetId([
                            'log_id' => $id,
                            'admin_id' => $id_arr[0],
                            'create_time' => time(),
                            'is_comment' => 0,
                            'status' => 4,
                            'type' => 0,
                        ]);

                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if (($result !== false) && ($insertall !== false) && ($inserts !== false) && ($insertss !== false)){
                    Db::commit();
                    $this->success('成功');
                }else{
                    Db::rollback();
                    $this->error(__('失败'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {

        $type = request()->param()['type'];
        $ids = request()->param()['id'];
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }


        $admin_arr = Db::table('fa_admin')
            ->field('nickname,avatar')
            ->where('id',$row->admin_id)
            ->find();

        if (empty($admin_arr)){
            $name = '';
        }else{
            $name = $admin_arr['nickname'].'提交的出差';
        }


        $detail = Db::table('fa_oa_route')
            ->where('oa_id',$row->id)
            ->select();


        if ($row->admin_id == $this->auth->id){
            $is = 1;
        }else{
            $is = 2;
        }

        $pan_arr = Db::table('fa_oa_relation')
            ->alias('a')
            ->field('a.id,b.nickname,b.avatar')
            ->join('fa_admin b','a.admin_id=b.id','left')
            ->where(['a.log_id'=>$row->id,'a.status'=>4,'a.type'=>1])
            ->select();


        $arr = Db::table('fa_admin')
            ->field('id,nickname,avatar')
            ->where('id','in',$row->ids)
            ->select();

        $data['status'] = '';
        $arrs = [];
        foreach ($arr as $k=>$v){
            $pan = Db::table('fa_oa_relation')
                ->where(['log_id'=>$row->id,'admin_id'=>$v['id'],'status'=>4,'type'=>0])
                ->find();

            if (empty($pan)){
                $status = '';
                $msg = '';
                $create_time = '';
            }else{

                if ($pan['is_comment'] == 0){
                    $status = '待审核';
                    $statuss = 1;
                }elseif ($pan['is_comment'] == 1){
                    $status = '审核通过';
                    $statuss = 2;
                }elseif ($pan['is_comment'] == 2){
                    $status = '审核驳回';
                    $statuss = 3;
                }else{
                    $status = '无';
                    $statuss = 0;
                }

                if ($v['id'] == $this->auth->id){
                    $iss = $pan['is_comment'];
                }else{
                    $iss = 1;
                }


                $msg = $pan['msg'];
                if (empty($pan['update_time'])){
                    $create_time = '';
                }else{
                    $create_time = date('Y-m-d H:i:s',$pan['update_time']);
                }

            }

            $arrs[$k] = [
                'nickname' => $v['nickname'],
                'avatar' => $v['avatar'],
                'create_time' => $create_time,
                'status' => $status,
                'statuss' => $statuss,
                'msg' => $msg,
            ];
        }

        $adim_arr = Db::table('fa_admin')
            ->where('id',$row->admin_id)
            ->find();


        $arr_z[0] = [
            'nickname' => $adim_arr['nickname'],
            'avatar' => $adim_arr['avatar'],
            'create_time' => date('Y-m-d H:i:s',$row->create_time),
            'status' => '发起申请',
            'statuss' => 0,
            'msg' => '',
        ];

        $arrss = array_merge($arr_z,$arrs);

        $row->image = explode(',',$row->images);

//        switch ($row->status){
//            case 0:
//                $status_name = '待审核';
//                break;
//            case 1:
//                $status_name = '审核通过';
//                break;
//            case 2:
//                $status_name = '审核驳回';
//                break;
//            default:
//                $status_name = '';
//                break;
//        }



        $this->view->assign("is", $is);
        $this->view->assign("iss", $iss);
        $this->view->assign("idsss", $row->ids);

        $this->view->assign("name", $name);
        $this->view->assign("row", $row);
        $this->view->assign("detail", $detail);
        $this->view->assign("pan_arr", $pan_arr);
        $this->view->assign("arrss", $arrss);
        $this->view->assign("counts", count($arrss));
        $this->view->assign("type", $type);
        //$this->view->assign("status_name", $status_name);

        //$this->view->assign("comment", $comment);
        return $this->view->fetch();
    }

    /**
     * 申请人
     *
     */
    public function get_comment(){
        $request = request()->param();

        $arr = Db::table('fa_admin')
            ->field('id,nickname,avatar')
            ->where('id','in',$request['ids'])
            ->select();

        $data['status'] = '';
        $arrs = [];
        foreach ($arr as $k=>$v){
            $pan = Db::table('fa_oa_relation')
                ->where(['log_id'=>$request['id'],'admin_id'=>$v['id'],'status'=>4,'type'=>0])
                ->find();

            if (empty($pan)){
                $status = '';
                $msg = '';
                $create_time = '';
            }else{

                if ($pan['is_comment'] == 0){
                    $status = '待审核';
                    $statuss = 1;
                }elseif ($pan['is_comment'] == 1){
                    $status = '审核通过';
                    $statuss = 2;
                }elseif ($pan['is_comment'] == 2){
                    $status = '审核驳回';
                    $statuss = 3;
                }else{
                    $status = '无';
                    $statuss = 0;
                }

                if ($v['id'] == $this->auth->id){
                    $iss = $pan['is_comment'];
                }


                $msg = $pan['msg'];
                if (empty($pan['update_time'])){
                    $create_time = '';
                }else{
                    $create_time = date('Y-m-d H:i:s',$pan['update_time']);
                }

            }

            $arrs[$k] = [
                'nickname' => $v['nickname'],
                'avatar' => $v['avatar'],
                'create_time' => $create_time,
                'status' => $status,
                'statuss' => $statuss,
                'msg' => $msg,
            ];
        }

        $adim_arr = Db::table('fa_admin')
            ->where('id',$request['admin_id'])
            ->find();


        $arr_z[0] = [
            'nickname' => $adim_arr['nickname'],
            'avatar' => $adim_arr['avatar'],
            'create_time' => date('Y-m-d H:i:s',$request['create_time']),
            'status' => '发起申请',
            'statuss' => 0,
            'msg' => '',
        ];

        $arrss = array_merge($arr_z,$arrs);

        $status_arr = $this->model->get($request['id']);

        switch ($status_arr->status){
            case 0:
                $status_name = '(待审核)';
                break;
            case 1:
                $status_name = '(审核通过)';
                break;
            case 2:
                $status_name = '(审核驳回)';
                break;
            default:
                $status_name = '';
                break;
        }

        $this->success($status_name,'',$arrss);

    }


}
